<template>
  <h1>num:{{ num }}</h1>
  <div @click="cheangenum">num 加</div>
  <hr />
  <h1>count:{{ count }}</h1>
  <div @click="changenum">changenum++</div>
  <hr />

  <div>姓名：{{ username }}</div>
  <div>年龄：{{ age }}</div>
  <div @click="changeType">外貌：{{ type }}</div>
  <hr />
  <div>{{ resverType }}</div>
  <hr />
  <User
    :username="username"
    :age="age"
    :description="description"
    @changeAge="changeAge"
    class="userCss"
  />

  <Student />
</template>

<script>

import { toRefs, reactive, ref, computed, watchEffect, watch, provide } from "vue";
import User from './components/User.vue';
import Student from './components/Student.vue';

export default {
  name: 'App',
  components: { User, Student },
  data() {
    return {
      count: 0
    }
  },

  methods: {
    changenum() {
      this.count++
    }
  },

  setup() {
    // ref
    let num = ref(0);

    function cheangenum() {
      num.value++
    }

    // reactive
    const user = reactive({
      age: 10,
      username: '江子',
      type: '帅!',
      description: '描述',
      resverType: computed(() => {
        return user.type.split('').reverse().join('')
      })
    });

    // 修改
    function changeType() {
      user.type = '超级帅!'
    }

    // 函数监听
    watchEffect(() => {
      console.log('type改变了,触发执行函数', user.type);
    })

    // 单独监听
    watch(num, (newNum, oldNum) => {
      console.log('num改变了,触发执行函数', newNum, oldNum);
    })

    // 多个监听
    watch([num, user], (newNum, oldNum) => {
      console.log('多个监听', newNum, oldNum);
    });

    const changeAge = (val) => {
      console.log('val', val);
      user.age = val
    }

    const student = ({
      name: "小红",
      classname: '一年级'
    });
    provide('student', student); // 导出 student (父组件传出)

    return {
      changeAge,
      num,
      cheangenum,
      changeType,
      ...toRefs(user),// 可以不使用user了
    }
  }
}
</script>
